var app = getApp();
var server = require('../../utils/server');
var common = require('../../utils/common');
var amapFile = require('../../libs/amap-wx.js');
//获取应用实例
Page({
  data: {
    menuButtontop: 20, //菜单按钮距离顶部距离
    menuButtonHeight: 32, //菜单按钮高度
    showTopTip: true,
    productList: [],
    storeInfo: [],
    isLocate: true,
    showAddr: false,
    classHeight: '',
    topHeight: "",
    location: '定位中...',
    storeId: "",
    cartNum: 0,
    showStorePop: false,
    scrollnum: '',
    showLoginPop: false,
    packetScene: '', //红包池场景值
    packetUrl: '', //红包请求api
    showAdPop: false,
    scene: "",
    curCompanyId: "",
    popImg: "",
    scrollleft: 'l0',
    mgt: 0,
    firClassList: [], //一级分类列表
    curSecClassList: [], //二级分类列表
    curClassBanner: "",
    curFirClassId: "",
    curSecClassId: "",
    curFirClassName: '', //一级分类名称
    curFirClassIndex: "",
    curSecClassIndex: "",
    pathFirClassId: "", //一级分类路径id
    pathSecClassId: "", //二级分类路径id
    isDisableLog: false,
    isShowBack: true,
    isShowHome: false,
    isLowVersion: false,
    refreshing: false,
    nomore: false,
    showChangeServicePop: false, //商圈仓切换弹窗
    showPickHourPop: false, //高峰期弹窗
    isChangeService: false
  },


  onLoad: function (options = {}) {
    app.globalData.refreshTag = true;
    this.data.pathFirClassId = options.category_id == undefined ? '' : options.category_id;
    this.data.pathSecClassId = options.sub_category_id == undefined ? '' : options.sub_category_id;
    console.log(options.scene)
    if (options.scene != undefined) {
      this.data.scene = options.scene;
      app.globalData.skipType = 0;
      if ((options.scene).indexOf('DECODE') > -1) { //判断是否特殊码进入
        this.data.decodescene = options.scene;
      } else {
        if (options.scene > 0) { //判断是否前置仓码进入
          app.globalData.companyid = options.scene;
          app.globalData.skipType = 0;
          wx.setStorage({
            key: 'companyid',
            data: app.globalData.companyid,
          })
        } else {
          app.globalData.companyid = "";
          wx.setStorage({
            key: 'companyid',
            data: app.globalData.companyid,
          })
        }

      }
    } else {
      app.globalData.companyid = "";
      wx.setStorage({
        key: 'companyid',
        data: app.globalData.companyid,
      })
      common.checkLogin().then(res => {
        if (res.errno == "0") {
          app.globalData.openid = res.data.openid;
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: () => {
              app.globalData.isGetWxUserinfo = true;
            }
          })
        }
      })
    }
    this.setData({
      isLocate: app.globalData.isLocate
    })
  },
  scrollList() {
    this.setData({
      showTopTip: false
    })
  },
  onHide: function () {
    wx.removeStorage({
      key: 'storeParams',
      success: function () {}
    })
    wx.removeStorage({
      key: 'tag',
      success: function () {}
    })
    wx.removeStorage({
      key: 'updateStoreArry',
      success: function () {}
    })
    app.globalData.isDeleteByStore = false;
    this.setData({
      showLoginPop: false
    })

  },
  onUnload() {
    console.log('onunload')
  },
  onShow: function () {
    this.setData({
      isShowHome: getCurrentPages().length == 1 ? true : false,
      isShowBack: getCurrentPages().length == 1 ? false : true
    })
    console.log(app.globalData.skipType, app.globalData.refreshTag,this.data.storeId)
    app.globalData.isGetCartByAdd = false;
    app.globalData.isFromCart = false;
    app.globalData.isChangeIndexLocation = false;
    this.setData({
      isLocate: app.globalData.isLocate
    })
    if (app.globalData.isLocate && app.globalData.refreshTag) {
      this.setData({
        scrollnum: 0
      })
      //定位获取门店信息
      if (app.globalData.skipType == 1) {
        if (app.globalData.latitude == null || app.globalData.longitude == null) {
          this.locateCur();
        } else {
          this.getStyle();
          this.getListByLaLon(app.globalData.latitude, app.globalData.longitude, app.globalData.city)
        }
      } else if (app.globalData.skipType == 2) {
        this.getStyle();
        wx.getStorage({
          key: 'storeId',
          success: res => {
            if (res.data != '0') {
              this.getListsByStoreId(res.data);
              this.data.storeId = res.data;
              this.getCartNum();
              this.setData({
                location: app.globalData.location,
                showAddr: false
              })
            } else {
              wx.hideNavigationBarLoading();
              this.setData({
                location: app.globalData.location,
                showAddr: true
              })
              wx.removeStorage({
                key: 'storeId',
                success: function () {},
              })
            }
          },
        })
      } else {
        if (this.data.decodescene != undefined) {
          this.decodeScene(this.data.decodescene);
        } else {
          this.locateCur();
        }
      }
    } else if (app.globalData.isLocate && !app.globalData.refreshTag) {
      this.getCartNum();
      var curStoreId=wx.getStorageSync('storeId');
      if(this.data.storeId!=curStoreId){
        wx.getStorage({
          key: 'storeId',
          success: res => {
            if (res.data != '0') {
              this.getListsByStoreId(res.data);
              this.data.storeId = res.data;
              this.getCartNum();
              this.setData({
                location: app.globalData.location,
                showAddr: false
              })
            } else {
              wx.hideNavigationBarLoading();
              this.setData({
                location: app.globalData.location,
                showAddr: true
              })
              wx.removeStorage({
                key: 'storeId',
                success: function () {},
              })
            }
          },
        })
      }else{
        if (!app.globalData.isDeleteByStore) {
          wx.hideNavigationBarLoading();
          wx.getStorage({
            key: 'updateStoreArry',
            success: res => {
              var storeid = res.data[0].storeid;
              if (storeid == this.data.storeId) {
                res.data.forEach((items) => {
                  this.data.productList.forEach((item, lindex) => {
                    if (item.goods_id == items.goodsid) {
                      this.setData({
                        ['productList[' + lindex + '].cart_num']: items.goodsnum
                      })
                    }
                  })
                })
              }
            },
          })
        } else if (app.globalData.isDeleteByStore) {
          wx.hideNavigationBarLoading();
          this.data.productList.forEach((item) => {
            item.cart_num = 0;
          })
          this.setData({
            productList: this.data.productList
          })
        } else {
          wx.hideNavigationBarLoading();
        }
      }
    } else {
      this.locateCur();
    }
  },
  //获取中间列表高度
  getStyle() {
    if (app.globalData.sdkversion > 210 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      this.setData({
        menuButtontop: wx.getMenuButtonBoundingClientRect().top == 0 ? 20 : wx.getMenuButtonBoundingClientRect().top,
        menuButtonHeight: wx.getMenuButtonBoundingClientRect().height
      })
    }
    this.setData({
      isLowVersion: app.globalData.wxversion > 700 ? false : true
    })
    if (app.globalData.sdkversion > 140) {
      wx.createSelectorQuery().select('.secclass-lists').boundingClientRect(res => {
        if (res != null) {
          this.setData({
            classHeight: wx.getSystemInfoSync().windowHeight - res.bottom
          })
        }
      }).exec()
      wx.createSelectorQuery().select('.top-cont').boundingClientRect(res => {
        if (res != null) {
          this.setData({
            mgt: res.bottom
          })
        }
      }).exec()
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用某些功能，请升级到最新微信版本后重试。'
      })
    }
  },
  //重新定位获取经纬度
  locateCur() {
    this.getStyle();
    var gdMap = new amapFile.AMapWX({
      key: common.gdKey
    });
    gdMap.getRegeo({
      success: res => {
        app.globalData.location = res[0].regeocodeData.pois[0] == undefined ? res[0].name : res[0].regeocodeData.pois[0].name;
        app.globalData.longitude = res[0].longitude;
        app.globalData.latitude = res[0].latitude;
        app.globalData.locateLongitude = res[0].longitude;
        app.globalData.locateLatitude = res[0].latitude;
        app.globalData.city = res[0].regeocodeData.addressComponent.city;
        app.globalData.locateCity = res[0].regeocodeData.addressComponent.city;
        app.globalData.locateProvince = res[0].regeocodeData.addressComponent.province;
        if (this.data.storeId != '') {
          this.getListsByStoreId(this.data.storeId)
        } else {
          this.getListByLaLon(res[0].latitude, res[0].longitude, app.globalData.city);
        }
        if (this.data.packetScene != '' && this.data.packetUrl != '') {
          common.checkLogin().then(res => {
            if (res.errno == "0") {
              app.globalData.isGetWxUserinfo = true;
              this.setData({
                showLoginPop: false
              })
              this.selectComponent("#redPacketsPool").showRedPackets();
              wx.setStorage({
                key: "sso",
                data: res.data.sso,
                success: () => {}
              })
              if (JSON.stringify(res.data.member) != "{}") {
                this.storageUserinfo(res.data);
              }
            } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
              this.setData({
                showLoginPop: true
              })
            } else {
              common.showErrorToast(res.errmsg)
            }
          })
        }
        app.globalData.addrId = null;
      },
      fail: () => {
        this.setData({
          isLocate: false
        })
      }
    })
  },
  //根据经纬度获取商品列表
  getListByLaLon(la, lon) {
    var returntype = "one";
    common.getStoreByLaLon(lon, la, returntype, app.globalData.city, "").then(res => {
      if (JSON.stringify(res.data) == "{}") {
        wx.hideNavigationBarLoading();
        this.setData({
          location: app.globalData.location,
          showAddr: true
        })
        wx.removeStorage({
          key: 'storeId',
          success: function () {},
        })
      } else if (JSON.stringify(res.data) != "{}" && res.errno == '0') {
        this.getListsByStoreId(res.data.store_id)
        this.setData({
          showAddr: false
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  //上报微信
  reportWx(curtarget) {
    if (app.globalData.scene != null && app.globalData.openid != null) {
      // 埋点 定位/选择门店
      app.actionReport('INIT', {
        scene_type: app.globalData.scene,
        business_type: 'O2O',
        openid: app.globalData.openid
      })
      app.actionReport('SET_BUSINESS_TYPE', {
        business_type: 'O2O'
      })
      app.actionReport('SET_STORE_ID', {
        // 门店ID(必须, 商户自己的门店ID, 这里仅做区分用)
        store_id: this.data.storeId,
        // 门店ID(必须, 门店名称)
        store_name: this.data.storeInfo.name,
        // 门店所在城市(可选)
        store_city: app.globalData.city,
      })
      app.actionReport('ADD_TO_CART', {
        // 商品ID(可选, 和条码二选一)
        sku_id: curtarget.id,
        // 商品名称(可选)
        sku_name: curtarget.name,
        // 商品价格(可选, 单位: 分)
        sku_price: parseFloat(curtarget.price) * 100,
      })
    }
  },
  // 根据门店id获取商品列表
  getListsByStoreId(storeId) {
    this.setData({
      location: app.globalData.location
    })
    wx.showNavigationBarLoading();
    common.showLoading();
    server.postJSON(common.storePath + "store/index/", {
      "store_id": storeId,
      "longitude": app.globalData.longitude,
      "latitude": app.globalData.latitude
    }, res => {
      if (res.data.errno == '0') {
        wx.hideNavigationBarLoading();
        common.hideLoading();
        let data = res.data.data,
          store = data.store;
        this.data.storeId = store.store_id;
        this.data.curCompanyId = store.company_id;
        //获取是否是商圈仓
        if (store.entity_store_id > 0) {
          this.checkServiceType(store.store_id);
        }
        if ((this.data.scene).indexOf('activity') > -1) {
          this.setData({
            showAdPop: true
          })
        }
        this.setData({
          storeInfo: store,
          popImg: data.banner[0].pic_url,
          showStorePop: data.store.status_tip.is_show == '1' ? true : false //门店其他状态提示（未开业、雨天）
        })
        this.getCartNum()
        wx.setStorage({
          key: 'storeId',
          data: store.store_id
        })
        var firClassList = data.category_list;
        if (firClassList != null) {
          this.setData({
            firClassList: firClassList
          })
          //获取商品列表
          if (this.data.pathFirClassId != '') {
            this.setData({
              curFirClassId: this.data.pathFirClassId
            })
            var cindex = firClassList.findIndex(item => item.category_id == this.data.curFirClassId);
            if (cindex > -1) {
              var classArry = firClassList.filter((item, index) => index == cindex);
              this.data.curFirClassName = classArry[0].name;
              this.data.curFirClassIndex = cindex;
              this.setData({
                scrollnum: 0,
                curClassBanner: classArry[0].pic_url,
                curSecClassList: classArry[0].child,
                scrollleft: 'sec' + this.data.curFirClassId
              })
              wx.showNavigationBarLoading();
              if (this.data.pathSecClassId != '') {
                var secindex = classArry[0].child.findIndex(item => item.category_id == this.data.pathSecClassId);
                this.data.curSecClassIndex = secindex;
                this.setData({
                  curSecClassId: this.data.pathSecClassId
                })
                this.getProductsByClass(this.data.curSecClassId);
              } else {
                var searchid = classArry[0].child.length > 0 ? classArry[0].child[0].category_id : this.data.curFirClassId;
                this.data.curSecClassIndex = classArry[0].child.length > 0 ? 0 : '';
                this.setData({
                  curSecClassId: classArry[0].child.length > 0 ? classArry[0].child[0].category_id : ''
                })
                if (classArry[0].child.length > 0) {}
                this.getProductsByClass(searchid);
              }
            } else {
              this.showHotLists(this.data.firClassList[0]);
            }
          } else {
            this.showHotLists(this.data.firClassList[0]);
          }
        } else {
          this.setData({
            firClassList: [],
            curSecClassList: []
          })
          wx.showToast({
            title: '该门店暂无商品',
            icon: "none"
          })
        }

      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  //默认展示商品列表
  showHotLists(firClassList) {
    this.data.curFirClassIndex = 0;
    this.data.curFirClassName = firClassList.name;
    this.setData({
      curSecClassList: firClassList.child.length > 0 ? firClassList.child : [],
      curClassBanner: firClassList.pic_url,
      curFirClassId: firClassList.category_id,
      curSecClassId: firClassList.child.length > 0 ? firClassList.child[0].category_id : '',
      scrollleft: 'sec' + firClassList.category_id
    })

    this.data.curSecClassIndex = firClassList.child.length > 0 ? 0 : '';
    var categoryid = firClassList.child.length > 0 ? firClassList.child[0].category_id : firClassList.category_id
    this.getProductsByClass(categoryid);
    this.data.curFirClassIndex = 0;
    app.globalData.refreshTag = false;
  },
  // 根据一级菜单查询商品
  getProducts: function (e) {
    var curTarget = e.currentTarget.dataset;
    this.setData({
      curSecClassList: curTarget.child,
      scrollleft: 'sec' + curTarget.id,
      showTopTip: false,
      curClassBanner: curTarget.picurl,
      curFirClassId: curTarget.id,
      scrollnum: 0,
      nomore: false,
      refreshing: false
    })
    var searchid = curTarget.child.length > 0 ? curTarget.child[0].category_id : this.data.curFirClassId;
    this.data.curSecClassIndex = curTarget.child.length > 0 ? 0 : '';
    this.data.curFirClassIndex = curTarget.index;
    this.data.curFirClassName = curTarget.name;
    this.setData({
      curSecClassId: curTarget.child.length > 0 ? curTarget.child[0].category_id : ''
    })
    this.getProductsByClass(searchid);
  },
  // 根据二级分类查看商品
  getProductsBySecClass(e) {
    var curTarget = e.detail.currentTarget.dataset;
    wx.showNavigationBarLoading();
    common.showLoading();
    this.setData({
      nomore: false,
      scrollnum: 0,
      refreshing: false
    })
    server.postJSON(common.storePath + 'store/categorygoods/', {
      "store_id": this.data.storeId,
      "category_id": curTarget.id
    }, res => {
      if (res.data.errno == '0') {
        app.globalData.refreshTag = false;
        wx.hideNavigationBarLoading();
        res.data.data.forEach((list) => {
          list.isCanAdd = true;
          list.isCanReduce = true;
        })
        this.data.curSecClassIndex = curTarget.index;
        this.setData({
          productList: res.data.data,
          curSecClassId: curTarget.id,
        });
        common.hideLoading();
        this.selectComponent("#prolist").reportUserTrace(this.data.storeId, this.data.curFirClassName, this.data.productList);
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  // 根据初始化分类查询商品
  getProductsByClass(classId) {
    wx.showNavigationBarLoading();
    common.showLoading();
    server.postJSON(common.storePath + 'store/categorygoods/', {
      "store_id": this.data.storeId,
      "category_id": classId
    }, res => {
      if (res.data.errno == '0') {
        wx.hideNavigationBarLoading();
        app.globalData.refreshTag = false;
        res.data.data.forEach((list) => {
          list.isCanAdd = true;
          list.isCanReduce = true;
        })
        this.setData({
          productList: res.data.data,
          scrollnum: 0
        });
        common.hideLoading();
        this.selectComponent("#prolist").reportUserTrace(this.data.storeId, this.data.curFirClassName, this.data.productList);
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })

  },
  loadMore(list) {
    this.data.productList = [];
    list.forEach((list) => {
      list.isCanAdd = true;
      list.isCanReduce = true;
    })
    this.setData({
      productList: list, //获取数据数组
      scrollnum: 0
    });
  },
  //分享事件
  onShareAppMessage() {
    var shareObj = {
      imageUrl: '../../imgs/share.jpg',
      path: '/pages/index/index',
      title: '健康三餐，1小时送到家'
    }
    return shareObj;
  },
  // 打开定位
  openLocation(e) {
    if (e.detail.errMsg == "openSetting:ok" && e.detail.authSetting['scope.userLocation']) {
      app.globalData.isLocate = true;
      wx.switchTab({
        url: '../index/index',
      })
    } else {
      common.showErrorToast('需要授权地理位置后使用！');
    }
  },
  //获取购物车数量
  getCartNum() {
    server.postJSON(common.storePath + 'cart/goodsnum', {
      "store_id": this.data.storeId,
      "is_deliverable": this.data.storeInfo.is_deliverable
    }, res => {
      if (res.data.errno == "0") {
        this.setData({
          cartNum: res.data.data.cart.num,
          cartData: res.data.data.cart
        })
      } else {
        common.showErrorToast(res.data.errmsg);
      }

    })
  },
  //隐藏门店状态弹框
  hideStorePop() {
    this.setData({
      showStorePop: false
    })
  },
  //去商品详情页
  goToProductDetail(e) {
    var curTarget = e.detail.currentTarget.dataset;
    let goodsId = curTarget.id,
      categoryid = curTarget.categoryid;
    wx.setStorageSync('curgoodsmesg', {
      'curtraceid': curTarget.traceid,
      'curgoodsscene': this.data.curFirClassName
    })
    app.globalData.formSceneId = '';
    wx.navigateTo({
      url: 'productDetail?id=' + goodsId + '&&storeId=' + this.data.storeId + '&&categoryid=' + categoryid
    })
  },
  // 添加购物车
  addCart: function (e) {
    var curTarget = e.detail.currentTarget.dataset;
    var goodIndex = curTarget.index,
      goodName = curTarget.name,
      goodprice = curTarget.price,
      traceid = curTarget.traceid;
    this.setData({
      ['productList[' + goodIndex + '].isCanAdd']: false
    })
    server.postJSON(common.storePath + 'cart/addgoods/', {
      "store_id": this.data.storeId,
      "goods_id": curTarget.id,
      "trace_id": traceid,
      "scene": this.data.curFirClassName
    }, res => {
      if (res.data.errno == "0") {
        this.reportWx(curTarget); //冰箱贴时上报微信
        common.showErrorToast("添加成功");
        this.setData({
          ['productList[' + goodIndex + '].cart_num']: parseInt(this.data.productList[goodIndex].cart_num) + 1,
          ['productList[' + goodIndex + '].isCanAdd']: true
        })
        this.getCartNum();
        wx.reportAnalytics('CLICK_PRODUCT', {
          product_id: curTarget.id,
          product_name: goodName,
          source_id: this.data.curFirClassName,
          coupon_stock_id: ''
        })
        wx.reportAnalytics('addcart_byproductslist', {
          goodsname: goodName,
          addgoodsnum: parseInt(this.data.productList[goodIndex].cart_num) + 1,
          removegoodsnum: '',
          curgoodsnum: parseInt(this.data.productList[goodIndex].cart_num),
          goodsprice: goodprice,
          cartnum: parseInt(this.data.cartNum) + 1
        });
      } else {
        this.setData({
          ['productList[' + goodIndex + '].isCanAdd']: true
        })
        if (res.data.errno == '100012') {
          this.setData({
            showLoginPop: true
          })
        } else {
          common.showErrorToast(res.data.errmsg);
        }

      }
    })
  },
  reduceEmpty() {
    console.log('waiting reduce success')
  },
  addEmpty() {
    console.log('waiting add success')
  },
  //商品数量减1
  reduceCart: function (e) {
    var curTarget = e.detail.currentTarget.dataset;
    var goodIndex = curTarget.index,
      goodName = curTarget.name,
      goodprice = curTarget.price,
      traceid = curTarget.traceid;
    this.setData({
      ['productList[' + goodIndex + '].isCanReduce']: false
    })
    this.getCartNum();
    server.postJSON(common.storePath + 'cart/decrease/', {
      "store_id": this.data.storeId,
      "goods_id": curTarget.id,
      "trace_id": traceid
    }, res => {
      if (res.data.errno == "0") {
        this.getCartNum();
        this.setData({
          ['productList[' + goodIndex + '].cart_num']: parseInt(this.data.productList[goodIndex].cart_num) - 1,
          ['productList[' + goodIndex + '].isCanReduce']: true
        })
        wx.reportAnalytics('addcart_byproductslist', {
          goodsname: goodName,
          addgoodsnum: '',
          removegoodsnum: parseInt(this.data.productList[goodIndex].cart_num) - 1,
          curgoodsnum: parseInt(this.data.productList[goodIndex].cart_num),
          goodsprice: goodprice,
          cartnum: parseInt(this.data.cartNum) - 1,
          curclassname: this.data.curFirClassName
        });
      } else {
        this.setData({
          ['productList[' + goodIndex + '].isCanReduce']: true
        })
        common.showErrorToast(res.data.errmsg);
      }

    })
  },

  goToCart() {
    app.globalData.isAccount = false;
    app.globalData.cartIndexType = 2;
    wx.navigateTo({
      url: '../cart/cartIndexSec',
    })
  },
  showProList() {
    this.getListsByStoreId(this.data.storeId);
    this.setData({
      showAddr: false
    })
  },
  goToOtherStore() {
    this.setData({
      showStorePop: false
    })
    wx.navigateTo({
      url: '../../shop/pages/changeStore',
    })
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false,
        isDisableLog: false
      })
      this.checkRegister();
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  checkRegister() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        app.globalData.isGetWxUserinfo = true;
        this.setData({
          showLoginPop: false
        })
        wx.setStorage({
          key: "sso",
          data: res.data.sso,
          success: () => {
            if (this.data.packetScene != '' && this.data.packetUrl != '') {
              this.selectComponent("#redPacketsPool").showRedPackets();
            }
          }
        })
        if (JSON.stringify(res.data.member) != "{}") {
          this.storageUserinfo(res.data);
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          showLoginPop: true
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  goToSearchGoods() {
    if (!this.data.showAddr) {
      app.globalData.refreshTag = false;
      wx.navigateTo({
        url: '../../shop/pages/searchProduct',
      })
    }

  },
  goToChangeAddr() {
    app.globalData.refreshTag = false;
    wx.navigateTo({
      url: '../../address_manage/pages/changeAddress',
    })
  },
  goToStore() {
    if (this.data.storeInfo.service_store_id == '0') {
      app.globalData.refreshTag = false;
      wx.navigateTo({
        url: '../../shop/pages/changeStore'
      })
    }
  },
  //解析scene
  decodeScene(scene) {
    server.postJSON(common.storePath + 'voucher/scenedecode/', {
      "scene": scene
    }, res => {
      var data = res.data;
      if (data.errno == '0') {
        wx.setStorage({
          key: 'companyid',
          data: data.data.company_id,
        })
        this.setData({
          packetScene: data.data.company_id,
          packetUrl: data.data.url
        })
        if (data.data.store_id != '' && data.data.store_id != '0') {
          this.data.storeId = data.data.store_id;
        }
        this.data.pathFirClassId = data.data.category_id > 0 ? data.data.category_id : '';
        this.data.pathSecClassId = data.data.sub_category_id > 0 ? data.data.sub_category_id : '';
        this.locateCur();
        if (data.data.channel_id != '') {
          wx.setStorage({
            key: 'channelid',
            data: data.data.channel_id
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  // 落地页弹窗跳转指定分类
  changeClassId() {
    var classId = "";
    if (this.data.curCompanyId == '1000000') { //厦门公司
      classId = "131";
    } else if (this.data.curCompanyId == '1000001') { //泉州公司
      classId = "132";
    } else if (this.data.storeId == '10000155') { //枋湖
      classId = "139";
    } else if (this.data.storeId == '10000102') { //龙山 
      classId = "132";
    } else if (this.data.storeId == '10000147') { //滨北
      classId = "138";
    } else {
      classId = "";
    }
    var cindex = this.data.firClassList.findIndex(item => item.category_id == classId);
    if (cindex > -1) {
      var classArry = this.data.firClassList.filter((item, index) => index == cindex);
      this.data.curFirClassName = classArry[0].name;
      this.data.heightArr = [];
      this.data.curFirClassIndex = cindex;
      this.setData({
        curFirClassId: classId,
        showAdPop: false
      })
      this.getProductsByClass(classId);
      this.data.scene = "";
    } else {
      this.setData({
        showAdPop: false
      })
    }
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../common/agreement',
    })
  },
  backPrev() {
    wx.navigateBack()
  },
  backHome() {
    wx.switchTab({
      url: '../index/index',
    })
  },

  //下拉加载上一分类
  refreshData: function () {
    this.setData({
      refreshing: true,
    })
    if (this.data.curSecClassIndex - 1 >= 0) {
      server.postJSON(common.storePath + 'store/categorygoods/', {
        "store_id": this.data.storeId,
        "category_id": this.data.curSecClassList[this.data.curSecClassIndex - 1].category_id
      }, res => {
        if (res.data.errno == '0') {
          this.setData({
            curSecClassId: this.data.curSecClassList[this.data.curSecClassIndex - 1].category_id,
            refreshing: false
          })
          this.data.curSecClassIndex = this.data.curSecClassIndex - 1;
          this.loadMore(res.data.data)
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      })
    } else {
      this.setData({
        refreshing: false
      })
    }
  },
  //上拉加载下一分类
  loadmoreData: function () {
    this.setData({
      refreshing: true
    })
    if (this.data.curSecClassIndex < this.data.curSecClassList.length - 1) {
      this.setData({
        nomore: false
      })
      server.postJSON(common.storePath + 'store/categorygoods/', {
        "store_id": this.data.storeId,
        "category_id": this.data.curSecClassList[this.data.curSecClassIndex + 1].category_id
      }, res => {
        if (res.data.errno == '0') {
          this.setData({
            curSecClassId: this.data.curSecClassList[this.data.curSecClassIndex + 1].category_id,
            refreshing: false,
            scrollnum: 0
          })
          this.data.curSecClassIndex = this.data.curSecClassIndex + 1;
          this.loadMore(res.data.data)
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      })
    } else {
      this.setData({
        nomore: true
      })
    }
  },
  //校验服务类型为心鲜送还是门店送
  checkServiceType(storeid) {
    server.postJSON(common.storePath + 'storetoentity/mergeArea/', {
      "city": app.globalData.city,
      "store_id": storeid,
      "longitude": app.globalData.longitude,
      "latitude": app.globalData.latitude
    }, res => {
      if (res.data.errno == '0') {
        if (res.data.data.is_show == 1) {
          if (res.data.data.show_type == 'select') {
            this.setData({
              showChangeServicePop: true
            })
          } else if (res.data.data.show_type == 'busy') {
            this.setData({
              showPickHourPop: true
            })
          }
        }
      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  touchstart(e) {
    this.data.touch_start = e.timeStamp;
  },
  touchend(e) {
    this.data.touch_end = e.timeStamp;
  },
  //修改服务类型
  changeServiceType(e) {
    var touchTime = this.data.touch_end - this.data.touch_start;
    if (this.data.storeInfo.entity_store_id > 0) {
      if (touchTime >= 300) {
        // 长按设置默认值
        console.log('长按')
        server.postJSON(common.storePath + 'storetoentity/deltempdefault/', '', res => {
          if (res.data.errno == '0') {
            server.postJSON(common.storePath + 'storetoentity/setdefault/', {
              "service_type": e.currentTarget.dataset.servicetype
            }, res => {
              if (res.data.errno == '0') {
                this.getListsByStoreId(this.data.storeId)
              } else {
                common.showErrorToast(res.data.errmsg)
              }
            })
          } else {
            common.showErrorToast(res.data.errmsg)
          }
        })

      } else {
        // 短按设置临时默认值
        server.postJSON(common.storePath + 'storetoentity/settempdefault/', {
          "service_type": e.currentTarget.dataset.servicetype
        }, res => {
          if (res.data.errno == '0') {
            this.setData({
              showChangeServicePop: false
            })
            this.getListsByStoreId(this.data.storeId)
          } else {
            common.showErrorToast(res.data.errmsg)
          }
        })
      }
    }
  },
  recordTempServiceType(e) {
    server.postJSON(common.storePath + 'storetoentity/settempdefault/', {
      "service_type": 'entity'
    }, res => {
      if (res.data.errno == '0') {
        this.setData({
          showPickHourPop: false
        })
        this.getListsByStoreId(this.data.storeId)
      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  recordServiceType(e) {
    server.postJSON(common.storePath + 'storetoentity/setdefault/', {
      "service_type": e.currentTarget.dataset.servicetype
    }, res => {
      if (res.data.errno == '0') {
        this.setData({
          showChangeServicePop: false
        })
        this.getListsByStoreId(this.data.storeId)
      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  }
})